package com.itheima.tlias84.exception;

import com.itheima.tlias84.utils.ResultUtil;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;

/**
 * 全局异常处理器：
 * 第一步 使用组合注解@RestControllerAdvice
 * 第二步 定义方法指定要捕获的异常以及处理异常后的统一返回值与Http响应码
 *
 * @RestControllerAdvice 相当于环绕通知controller
 * 原因：因为我们无法使用try-catch捕获进入controller之前的异常，
 * 但是我们可以使用aop切面，在controller调用之前，进行增强：捕获异常，再进入controller
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultUtil handleArithmeticException(ArithmeticException exception){
        //注解1：标识需要捕获的异常@ExceptionHandler(需要捕获的异常.class)
        //注解1：指定响应状态码@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        return ResultUtil.fail(exception.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultUtil handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        //参数：需要捕获的异常对象
        String message = e.getFieldError().getDefaultMessage();
        Object value = e.getFieldError().getRejectedValue();

        //获取全部校验信息
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringJoiner joiner = new StringJoiner(",", "[", "]");
        for (FieldError fieldError : fieldErrors) {
            joiner.add(fieldError.getDefaultMessage());
        }
        return ResultUtil.fail(joiner.toString());
    }
}
